/**
 * @ClassName Offer12
 * @Description 剑指 Offer 12. 矩阵中的路径
 * @Author clockTown
 * @Date 2021/8/25 9:40
 * @Version 1.0
 */
class Offer12 {
}

/**
 * v0
 */
class Offer12V0 {
    public boolean exist(char[][] board, String word) {
        char[] chars = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == chars[0]){
                    boolean res = isExist(board, chars, 0, i, j);
                    if (res){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean isExist(char[][] board, char[] chars, int idx, int row, int col){
        if (row < 0 || row >= board.length || col < 0 || col >= board[0].length || board[row][col] != chars[idx]){
            return false;
        }

        if (idx == chars.length - 1){
            return true;
        }
        board[row][col] = '\0';
        boolean res = isExist(board, chars, idx + 1, row , col - 1) ||
                isExist(board, chars, idx + 1, row, col + 1) ||
                isExist(board, chars, idx + 1, row - 1, col) ||
                isExist(board, chars, idx + 1, row + 1, col);
        board[row][col] = chars[idx];
        return res;
    }
}